// var surveyingCtl = require('../controller/controller.surveying.js');
// var roadshowCtl = require('../controller/controller.roadshow.js');
// var strategyCtl = require('../controller/controller.strategy-meeting.js');
// var recommondCtl = require('../controller/controller.recommond.js');
// var otherCtl = require('../controller/controller.other-service.js');
// var sellerCtl = require('../controller/controller.seller.js');
// var evaluateCtl = require('../controller/controller.evaluate.js')
var userCtl = require('../controller/controller.user.js');
//var scheduleSevice = require('../services/service.schedule.js');
var wx = require('../utils/wx');
//{
//    "code": "200",
//    "msg": "success",
//    "obj": [
//        {
//            "rowId": "b229554d-1116-48c6-82ec-826be3d19ee4",
//            "sellerName": "zhangsan",
//            "surveyingCount": 1,
//            "roadshowoCount": 2,
//            "recommondCount": 2,
//            "strategymeetingCount": null,
//            "otherserviceCount": 1
//        },
//        {
//            "rowId": "b229554d-1116-48c6-82ec-826be3d19ee42",
//            "sellerName": "lisi",
//            "surveyingCount": null,
//            "roadshowoCount": null,
//            "recommondCount": null,
//            "strategymeetingCount": 1,
//            "otherserviceCount": 1
//        }
//    ]
//}

module.exports = {
    getWxUser: function (wxcode, callback) {
        var that = this;
        wx.getUserInfo(wxcode,function (err, userinfo) {
            if(userinfo){
                callback(null, {"userId":userinfo.UserId});
            }else{
                console.log(err);
                callback(err, null);
            }
        });
    },
    checkSession: function (req, res, next) {
        //所有跳转到home都通过当前入口
        if (req.session && req.session.uid) {

            ////20170625 注释teamid相关行为，直接放行到home
            // //如果有teamid，则放行至
            // if (req.session.teamId){
            //     console.log("   checkSession:### alread has teamid:" + req.session.teamId);
            //     next({
            //         'uid': req.session.uid,
            //         'teamId': req.session.teamId,
            //         moment: require("moment")
            //     });
            // }
            // //否则到teamselect页面进行team设置
            // else{
            //     console.log("   checkSession:### try to jump to teamselect to get Teamid");
            //     res.redirect('/smtool_project/wxapp/teamselect')
            // }
            next({
                'uid': req.session.uid,
                // 'teamId': req.session.teamId,
                moment: require("moment")
            });

        }
        //如果有code说明是企业号进入
        else if (req.query.code) {
            var wxCode = req.query.code;

            //1.通过wxCode换取公众号具体用户信息
            this.getWxUser(wxCode,function (err,data) {
                //2.根据公众号用户信息，匹配查找本地用户信息
                if (err){
                    res.redirect('/error');
                    return;
                }
                var rowId = data.userId;
                userCtl.getInfo({rowId:rowId},function (err,result) {
                    if (err) {
                        console.log(err);
                        req.session.uid = undefined;
                        req.session.userinfo = undefined;
                        res.redirect('/error');
                        return;
                    }
                    var user = result.obj;
                    if (user && user.rowId) {
                        if(!user.extension){
                            wx.getUserDetail(rowId,function (err,detail) {
                                if (err){
                                    res.redirect('/error');
                                    return;
                                }
                                userCtl.update({name : user.name, rowId : user.rowId, extension : detail.avatar},function(err,resp){});
                            });
                        }
                        req.session.uid = user.rowId;
                        req.session.userinfo = user;
                        // req.session.teamId = undefined;//重置teamid
                        req.session.channelportal = 'wx';
                        res.redirect('/smtool_project/wxapp/');
                        // next({
                        //     'uid': req.session.uid,
                        //     moment: require("moment")
                        // });
                    } else {
                        res.redirect('/error');
                    }
                });
            });
        }
        //否则就是正常登录
        else if (req.body.username && req.body.userpwd) {
            // console.log(params);

            var paramsLogin = {};
            paramsLogin.weid = req.body.username;
            paramsLogin.password = req.body.userpwd;
            // console.log(paramsLogin);
            userCtl.getInfoByPWD(paramsLogin, function (err, result) {
                if (err) {
                    console.log(err);
                    req.session.uid = undefined;
                    req.session.userinfo = undefined;
                    // req.session.teamId = undefined;
                    res.redirect('/smtool_project/wxapp/login');
                    return;
                }
                if (result.obj && result.obj.rowId) {
                    req.session.uid = result.obj.rowId;
                    req.session.userinfo = result.obj;
                    // req.session.teamId = undefined;//重置teamid

                    req.body.username = null;
                    req.body.userpwd = null;
                    res.redirect('/smtool_project/wxapp/')
                    // next({
                    //     'uid': req.session.uid,
                    //     moment: require("moment")
                    // });
                } else {
                    res.redirect('/smtool_project/wxapp/login');
                }
            })
        }
        else {
            next({
                'uid': undefined,
                moment: require("moment")
            });
        }
    },

    ////20170625 注释teamid相关行为，直接放行到home
    // checkTeam: function (req, res, next) {
    //
    //
    //     //如果是teamid已经选择，则跳到checkSession，由checkSession跳到home
    //     if (req.query.teamid){
    //         console.log("   checkTeam:### get teamid:" + req.query.teamid);
    //         req.session.teamId = req.query.teamid;
    //         res.redirect('/smtool_project/wxapp/')
    //     }
    //     //否则放行
    //     else{
    //         console.log("   checkTeam:### try to Get Teamid");
    //         req.query.userId = req.session.uid;
    //         scheduleSevice.getTeamListByUid(req,null,function (teamListResult) {
    //
    //             if (teamListResult && teamListResult.obj && teamListResult.obj.length > 0){
    //                 console.log(teamListResult);
    //                 next({
    //                     'uid': req.session.uid,
    //                     'teamInfo':teamListResult,
    //                     moment: require("moment")
    //                 });
    //             }else{
    //                 req.session.teamId = '00000001-0001-0001-0001-000000000001';//默认分组的teamid
    //                 res.redirect('/smtool_project/wxapp/')
    //             }
    //
    //
    //         })
    //     }
    //
    // },
}
;
